package com.jack.lib.ui.widget;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.jack.lib.ui.adapter.JRMoreAdapter;
import com.jack.lib.ui.R;
import com.jack.lib.ui.adapter.JViewHolder;
import com.jack.lib.ui.common.PhotoUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.util.SmartGlideImageLoader;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2020/6/4
 * desc   :
 */
public class AddPhotoView extends JFrameLayout {

    private int defaultResult = 1000;

    private static final int MODE_EDIT = 1;
    private static final int MODE_PREVIEW = 2;

    private final JRecyclerView mRecyclerView;
    private final MyMoreAdapter mAdapter;
    private int mMaxCount;
    private int mSpec;
    private int mMode;
    private String mHintText;
    private OnItemClickListener mOnItemClickListener;
    private Class<? extends IPhoto> mDataClass;


    @SuppressLint("ResourceType")
    public AddPhotoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AddPhotoView);

        mMaxCount = typedArray.getInt(R.styleable.AddPhotoView_JMaxCount, 9);
        mSpec = typedArray.getInt(R.styleable.AddPhotoView_JSpec, 4);
        mMode = typedArray.getInt(R.styleable.AddPhotoView_JMode, 1);

        if (mMaxCount <= 0) {
            throw new IllegalStateException("mMaxCount 不能小于或等于0");
        }
        mHintText = typedArray.getString(R.styleable.AddPhotoView_JHiText);
        if (TextUtils.isEmpty(mHintText)) {
            mHintText = "添加图片";
        }

        if (getId() != NO_ID){
            defaultResult = getId() & 0xffff;
        }

        typedArray.recycle();

        LayoutInflater.from(context).inflate(R.layout.view_add_photo, this, true);

        mRecyclerView = (JRecyclerView) findViewById(R.id.jRecyclerView);
        mRecyclerView.setLayoutManager(new GridLayoutManager(context, mSpec));
        mAdapter = new MyMoreAdapter();

        checkFooterItem();

        if (mMode == MODE_EDIT){
            helper.attachToRecyclerView(mRecyclerView);
        }
        mRecyclerView.setAdapter(mAdapter);
    }

    public void setData(Collection<IPhoto> collection){
        mAdapter.getData().clear();
        checkFooterItem();
        addData(collection);
    }

    public void addData(Collection<IPhoto> collection) {
        for (IPhoto photo : collection) {
            addData(photo);
        }
    }

    public void clearData(){
        mAdapter.getData().clear();
        checkFooterItem();
    }


    public void addData(IPhoto photo) {
        mAdapter.addData(Math.max(mAdapter.getData().size() - 1, 0), new ItemEntity(photo));
        if (mAdapter.getData().size() > mMaxCount) {
            mAdapter.removeAt(mMaxCount);
        }
    }

    public <T extends IPhoto> void setDataClass(Class<T> dataClass) {
        mDataClass = dataClass;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) throws InstantiationException,
            IllegalAccessException {
        if (requestCode == defaultResult && resultCode == Activity.RESULT_OK && data != null){
            List<String> strings = PhotoUtils.INSTANCE.obtainSimpleResult(data);

            for (String string : strings) {
                IPhoto photo = mDataClass == null ? new Photo() : mDataClass.newInstance();
                photo.setPath(string);
                addData(photo);
            }
        }
    }

    public List<String> getPathList(){
        List<String> list = new ArrayList<>();
        for (ItemEntity entity : mAdapter.getData()) {
            if (entity.itemType == ItemEntity.BODY){
                list.add(entity.photo.getPath());
            }
        }
        return list;
    }

    public List<IPhoto> getData(){
        List<IPhoto> list = new ArrayList<>();
        for (ItemEntity entity : mAdapter.getData()) {
            if (entity.itemType == ItemEntity.BODY){
                list.add(entity.photo);
            }
        }
        return list;
    }


    private void checkFooterItem() {
        for (ItemEntity bean : mAdapter.getData()) {
            if (bean.itemType == ItemEntity.ADD) {
                return;
            }
        }
        if (mMode == MODE_EDIT){
            mAdapter.addData(new ItemEntity(ItemEntity.ADD));
        }
    }

    private class MyMoreAdapter extends JRMoreAdapter<ItemEntity> {

        public MyMoreAdapter() {
            addItemType(ItemEntity.BODY, R.layout.adapter_add_photo);
            addItemType(ItemEntity.ADD, R.layout.view_add_photo_footer);
        }

        @Override
        protected void convert(JViewHolder holder, ItemEntity itemEntity) {

            switch (itemEntity.getItemType()) {
                case ItemEntity.BODY:
                    holder.loadImageUrl(R.id.img, itemEntity.photo.getPath());
                    holder.setVisible(R.id.delete, mMode == MODE_EDIT);
                    holder.getView(R.id.delete).setOnClickListener(v -> {
                        removeAt(holder.getLayoutPosition());
                        //如果没有尾部, 则添加一个尾部
                        checkFooterItem();
                    });
                    holder.itemView.setOnClickListener(v -> {
                        //查看
                        if (mOnItemClickListener != null){
                            mOnItemClickListener.onItemClick(itemEntity.photo.getPath(), v.findViewById(R.id.img), holder.getLayoutPosition());
                        }else {
                            new XPopup.Builder(getContext())
                                    .asImageViewer(v.findViewById(R.id.img), itemEntity.photo.getPath(), new SmartGlideImageLoader())
                                    .show();
                        }
                    });
                    break;
                case ItemEntity.ADD:
                    holder.setText(R.id.text, mHintText);
                    holder.itemView.setOnClickListener(v -> {
                        //选择图片拍照
                        PhotoUtils.INSTANCE.openPhoto(((Activity) getContext()), mMaxCount - getItemCount() + 1, defaultResult, true, false, false);
                    });
                    break;
            }
        }
    }


    public void setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(String url, View itemView, int position);
    }

    static class ItemEntity implements MultiItemEntity {

        private static final int BODY = 1;
        private static final int ADD = 2;

        private int itemType;

        IPhoto photo;

        public ItemEntity(IPhoto photo) {
            this.photo = photo;
            this.itemType = BODY;
        }

        public ItemEntity(int itemType) {
            this.itemType = itemType;
        }

        @Override
        public int getItemType() {
            return itemType;
        }
    }


    ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {

            ItemEntity itemBean = mAdapter.getData().get(viewHolder.getLayoutPosition());
            int dragFrlg = 0;
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            } else if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            }
            if (itemBean.itemType == ItemEntity.ADD) {
                dragFrlg = 0;
            }
            return makeMovementFlags(dragFrlg, 0);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {

            //得到当拖拽的viewHolder的Position
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();

            if (mAdapter.getData().get(toPosition).itemType == ItemEntity.ADD) {
                return false;
            }

            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(mAdapter.getData(), i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(mAdapter.getData(), i, i - 1);
                }
            }
            mAdapter.notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            //侧滑删除可以使用；
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return true;
        }

        /**
         * 长按选中Item的时候开始调用
         * 长按高亮
         * @param viewHolder
         * @param actionState
         */
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                ObjectAnimator animatorX = ObjectAnimator.ofFloat(viewHolder.itemView, "scaleX", 1, 1.1f).setDuration(100);
                ObjectAnimator animatorY = ObjectAnimator.ofFloat(viewHolder.itemView, "scaleY", 1, 1.1f).setDuration(100);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.playTogether(animatorX, animatorY);
                animatorSet.start();
                //获取系统震动服务//震动70毫秒
                Vibrator vib = (Vibrator) getContext().getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(70);
            }
            super.onSelectedChanged(viewHolder, actionState);
        }

        /**
         * 手指松开的时候还原高亮
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            ObjectAnimator animatorX = ObjectAnimator.ofFloat(viewHolder.itemView, "scaleX", 1.1f, 1.0f).setDuration(100);
            ObjectAnimator animatorY = ObjectAnimator.ofFloat(viewHolder.itemView, "scaleY", 1.1f, 1.0f).setDuration(100);
            AnimatorSet animatorSet = new AnimatorSet();
            animatorSet.playTogether(animatorX, animatorY);
            animatorSet.start();
        }
    });

    public interface IPhoto {

        void setPath(String path);

        String getPath();
    }

    public static class Photo implements IPhoto {

        private String path;

        @Override
        public void setPath(String path) {
            this.path = path;
        }

        @Override
        public String getPath() {
            return this.path;
        }
    }

}

